package com.etl.borrow.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.etl.base.BaseController;
import com.etl.borrow.enums.BorrowStatus;
import com.etl.borrow.model.Borrow;
import com.etl.borrow.service.IBorrowService;
import com.xr.annotation.RemoteService;
import com.xr.dto.ResultDto;
import com.xr.enums.RepaymentMode;
import com.xr.util.Assert;
import com.xr.util.DateUtil;
import com.xr.util.Utils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * <p>
 * 借款项目 前端控制器
 * </p>
 *
 * @author Arnold Yang
 * @since 2018-03-24
 */
@Controller
@RequestMapping("/borrow")
public class BorrowController extends BaseController {

  @RemoteService
  private IBorrowService borrowService;

  @ResponseBody
  @RequestMapping("/detail")
  public Borrow borrowDetail(Long borrowId) throws Exception {
    Assert.largeThanZero(borrowId, "标的不存在");

    Borrow borrow = borrowService.selectById(borrowId);
    Assert.notNull(borrow, "标的不存在");

    return borrow;
  }

  @ResponseBody
  @RequestMapping("/update")
  public Borrow borrowUpdate(Borrow borrowInfo) throws Exception {
    Assert.notNull(borrowInfo, "参数不合法");
    Assert.largeThanZero(borrowInfo.getBorrowId(), "标的不存在");

    EntityWrapper<Borrow> wrapper = new EntityWrapper<Borrow>();
    wrapper.where("borrow_id = {0}", borrowInfo.getBorrowId());

    Borrow borrow = borrowService.update(borrowInfo, wrapper);

    return borrow;
  }

  @ResponseBody
  @RequestMapping("/apply")
  public ResultDto borrowApply(Borrow borrowInfo) throws Exception {
    // validate
    Assert.notNull(borrowInfo, "借款信息必填");
    Assert.hasLength(borrowInfo.getTitle(), "借款标题必填");
    Assert.notNull(borrowInfo.getRepaymentType(), "还款方式必填");
    Assert.largeThanZero(borrowInfo.getAmount(), "借款金额必须大于0");
    Assert.largeThanZero(borrowInfo.getPeriod(), "借款期数必须大于0");
    Assert.largeThanZero(borrowInfo.getApr(), "借款利率必须大于0");

    // set default value
    borrowInfo.setUserId(super.getSessionUserId());
    long borrowId = borrowService.apply(borrowInfo);

    return super.success("标的创建成功", Utils.newHashMap("borrowId", borrowId));
  }

  /**
   * 可投资标的列表
   * @param page 第几页，默认1
   * @param rows 每页多少行，默认10
   * @return
   * @throws Exception
   */
  @ResponseBody
  @RequestMapping("/available/list")
  public List borrowList(
          @RequestParam(defaultValue = "1") int page,
          @RequestParam(defaultValue = "10")int rows) throws Exception {

    EntityWrapper<Borrow> wrapper = new EntityWrapper<Borrow>();
    wrapper.where("status = {0}", BorrowStatus.IN_BID.getCode());

    return borrowService.selectPage(new Page<Borrow>(page, rows), wrapper).getRecords();
  }
}

